package encoder

import (
	"bytes"
	"errors"
	"github.com/pion/rtp"
)

var ErrMorePacketsNeeded = errors.New("need more packets")

type RtpDecoder struct {
	SampleRate int

	buffer             bytes.Buffer
	timestamp          uint32 // 时间戳
	lastSequenceNumber uint16
}

// Init initializes the decoder.
func (d *RtpDecoder) Init() error {
	return nil
}

func (d *RtpDecoder) Decode(packet *rtp.Packet) ([][]byte, error) {
	if d.buffer.Len() > 0 && packet.SequenceNumber != (d.lastSequenceNumber+1) {
		// loss
	}

	if packet.Timestamp != d.timestamp && d.buffer.Len() > 0 {
		d.buffer.Reset()
	}

	d.timestamp = packet.Timestamp
	d.lastSequenceNumber = packet.SequenceNumber
	d.buffer.Write(packet.Payload)

	if packet.Marker {
		data := d.buffer.Bytes()

		d.buffer.Reset()

		return [][]byte{data}, nil
	}

	return nil, ErrMorePacketsNeeded
}
